<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class MembershipProduct extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'type',
        'duration',
        'price',
        'original_price',
        'icon',
        'purchase_url',
        'is_featured',
        'badge',
        'sort_order',
        'is_active',
    ];

    protected $casts = [
        'price' => 'float',
        'original_price' => 'float',
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
    ];

    /**
     * 获取会员类型名称
     */
    public function getTypeNameAttribute()
    {
        $types = [
            'day' => '日卡',
            'month' => '月卡',
            'year' => '年卡',
            'permanent' => '永久卡'
        ];

        return $types[$this->type] ?? $this->type;
    }

    /**
     * 获取折扣百分比
     */
    public function getDiscountPercentAttribute()
    {
        if ($this->original_price <= 0) {
            return 0;
        }
        
        $discount = 100 - round(($this->price / $this->original_price) * 100);
        return $discount > 0 ? $discount : 0;
    }

    /**
     * 获取活跃的会员产品列表
     */
    public static function getActiveProducts()
    {
        return self::where('is_active', true)
                   ->orderBy('sort_order')
                   ->get();
    }

    /**
     * 根据会员类型获取产品
     */
    public static function getByType($type)
    {
        return self::where('type', $type)
                   ->where('is_active', true)
                   ->first();
    }
}